//
//  GetMeeageView.m
//  mendianjieke
//
//  Created by 响当当 on 8/1/19.
//  Copyright © 2019 dongzheng. All rights reserved.
//

#import "GetMeeageView.h"

@interface GetMeeageView()<UITextFieldDelegate>
{
    
    dispatch_source_t _timer;
    
}
@property (nonatomic, strong)UILabel *titleLabel;//标题
@property (nonatomic, strong)UIButton *sendMessageBtn;//发送短信
@property (nonatomic, strong)UIButton *loginButton;//登录

@property (nonatomic, strong)NSMutableArray *textFieldArr;
@property (nonatomic, strong)NSString *phoneNum;

@end

@implementation GetMeeageView

- (NSMutableArray *)textFieldArr
{
    if (!_textFieldArr)
    {
        _textFieldArr = [[NSMutableArray alloc]init];
    }
    return _textFieldArr;
}

- (UILabel *)titleLabel
{
    if (!_titleLabel)
    {
        UILabel *titleLabel = [Utilties creatLabelWithFrame:CGRectMake(30*kUIScaleBasePlus,30*kUIScaleBasePlus,200*kUIScaleBasePlus,35*kUIScaleBasePlus)
                                               textAligment:NSTextAlignmentLeft
                                                   textClor:LCHexColor(0x282828)
                                                   textFont:25*kUIScaleBasePlus];
        titleLabel.text = @"请输入验证码";
        [self addSubview:titleLabel];
        
        
        _titleLabel = [Utilties creatLabelWithFrame:CGRectMake(30*kUIScaleBasePlus,CGRectGetMaxY(titleLabel.frame)+10*kUIScaleBasePlus,SCREEN_WIDTH-60*kUIScaleBasePlus,20*kUIScaleBasePlus)
                                       textAligment:NSTextAlignmentLeft
                                           textClor:LCHexColor(0x282828)
                                           textFont:14*kUIScaleBasePlus];
    }
    return _titleLabel;
}

- (UIButton *)sendMessageBtn
{
    if (!_sendMessageBtn)
    {
        _sendMessageBtn = [Utilties creatButtonWithFrame:CGRectMake(30*kUIScaleBasePlus,CGRectGetMaxY(self.titleLabel.frame)+97*kUIScaleBasePlus,100*kUIScaleBasePlus,20*kUIScaleBasePlus)
                                            textAligment:UIControlContentHorizontalAlignmentLeft
                                                    text:@"重新发送"
                                                textClor:LCHexColor(0xFFBA87)
                                               buttonBGC:[UIColor clearColor]
                                                textFont:14*kUIScaleBasePlus
                                                  target:self
                                                  method:@selector(sendMessage)];
    }
    return _sendMessageBtn;
}

- (UIButton *)loginButton
{
    if (!_loginButton)
    {
        _loginButton = [Utilties creatButtonWithFrame:CGRectMake(30*kUIScaleBasePlus,CGRectGetMaxY(self.titleLabel.frame)+166*kUIScaleBasePlus,315*kUIScaleBasePlus,40*kUIScaleBasePlus)
                                         textAligment:UIControlContentHorizontalAlignmentCenter
                                                 text:@"登录"
                                             textClor:LCHexColor(0xFFFFFF)
                                            buttonBGC:LCHexColor(0xFFBA87)
                                             textFont:17*kUIScaleBasePlus
                                               target:self
                                               method:@selector(login)];
        _loginButton.layer.masksToBounds = YES;
        _loginButton.layer.cornerRadius = _loginButton.frame.size.height/2;
        _loginButton.enabled = NO;
        
    }
    return _loginButton;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        
        [self addSubview:self.titleLabel];
        [self addSubview:self.sendMessageBtn];
        [self addSubview:self.loginButton];
        [self creatTextField];
        [self addSubview:self.sendMessageBtn];
        [self addSubview:self.loginButton];
    }
    return self;
}


- (void)creatTextField
{
    CGFloat margin = 30*kUIScaleBasePlus;
    CGFloat width = 50*kUIScaleBasePlus;
    
    for (int i=0; i<4; i++)
    {
        UITextField *textField = [[UITextField alloc]initWithFrame:CGRectMake(30*kUIScaleBasePlus+i*(margin+width),CGRectGetMaxY(self.titleLabel.frame)+41*kUIScaleBasePlus,width,30*kUIScaleBasePlus)];
        textField.delegate = self;
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.textAlignment = NSTextAlignmentCenter;
        textField.textColor = LCHexColor(0x282828);
        textField.layer.borderWidth = 1;
        if (i == 0)
        {
            textField.layer.borderColor = LCHexColor(0xFF7A17).CGColor;
            [textField becomeFirstResponder];
        }
        else
        {
            textField.layer.borderColor = LCHexColor(0xE5E5E5).CGColor;
        }
        textField.tag = i;
//        [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventAllEvents];
        [self.textFieldArr addObject:textField];
        [self addSubview:textField];
    }
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(110*kUIScaleBasePlus,CGRectGetMaxY(self.titleLabel.frame)+41*kUIScaleBasePlus,SCREEN_WIDTH,30*kUIScaleBasePlus)];
    footView.backgroundColor = [UIColor clearColor];
    [self addSubview:footView];
}

#pragma mark - Method

//- (void)textChange:(UITextField *)textField
//{
//    return;
//}

- (void)sendMessage
{
    [self sentPhoneCodeTimeMethod];
    [self sendMessage:self.phoneNum];
}

- (void)login
{
    [self endEditing:YES];
    
    NSDictionary *pramaters = @{
                                @"phoneNum" : self.phoneNum,
                                @"code" : @"232323",
                                };
    
    WeakSelf(self)
    [SVProgressHUD showWithStatus:nil];
    [infoManager getLoginRequestWithParamers:pramaters sucess:^{
        DISMISS_SVP(1.0f);
        LCUserDefaultsSet(current_User.username,kLoginUser);
        UIViewController *topRootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        while (topRootViewController.presentedViewController)
        {
            topRootViewController = topRootViewController.presentedViewController;
        }
        
        [topRootViewController dismissViewControllerAnimated:YES completion:^{
            
        }];
    } fail:^(NSError *error) {
        DISMISS_SVP(1.0f);
    }];
}

- (void)getPhoneNum:(NSString *)phone
{
    NSString *str = [NSString stringWithFormat:@"验证码已发送至+86%@",phone];
    self.titleLabel.attributedText = [str addAttriButedString:str
                                                        Color:LCHexColor(0xFF7A17)
                                                         Font:[UIFont systemFontOfSize:14*kUIScaleBasePlus]
                                                         rang:NSMakeRange(str.length-phone.length,phone.length)];
    [self sendMessage:phone];
    self.phoneNum = phone;
    
}

//倒计时
- (void)sentPhoneCodeTimeMethod
{
    
    //倒计时时间 - 60秒
    __block NSInteger timeOut = 59;
    //执行队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //计时器 -》dispatch_source_set_timer自动生成
     _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        if (timeOut <= 0) {
            dispatch_source_cancel(_timer);
            //主线程设置按钮样式-》
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.sendMessageBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                [self.sendMessageBtn setTitleColor:LCHexColor(0xFF7A17) forState:UIControlStateNormal];
                [self.sendMessageBtn.titleLabel setTextAlignment:NSTextAlignmentLeft];
                [self.sendMessageBtn setUserInteractionEnabled:YES];
            });
        }else{
            //开始计时
            //剩余秒数 seconds
            NSInteger seconds = timeOut % 60;
            NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds];
            //主线程设置按钮样式
            dispatch_async(dispatch_get_main_queue(), ^{
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1.0];
                [self.sendMessageBtn setTitle:[NSString stringWithFormat:@"%@S后重新发送",strTime] forState:UIControlStateNormal];
                [self.sendMessageBtn setTitleColor:LCHexColor(0x8B8B8B) forState:UIControlStateNormal];
                self.sendMessageBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
                [UIView commitAnimations];
                //计时器件不允许点击
                [self.sendMessageBtn setUserInteractionEnabled:NO];
            });
            
            timeOut--;
        }
    });
    
    dispatch_resume(_timer);
}

- (void)cancelTime
{
    dispatch_source_cancel(_timer);
}

- (void)sendMessage:(NSString *)phoneNum
{

    [infoManager getCodeWithPhone:phoneNum
                           Sucess:^(id  _Nonnull acceptData) {
                               
                           }
                             fail:^(NSError * _Nullable error) {
                                 
                             }];
}

#pragma mark - textField delegate


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    if (string.length == 1)
    {
        UITextField *nextTextField = nil;
        if (self.textFieldArr.count-1 == textField.tag)
        {
            textField.text = string;
            self.loginButton.enabled = YES;
            [self.loginButton setBackgroundColor:LCHexColor(0xFF7A17)];
            return NO;
        }
        else
        {
            nextTextField = self.textFieldArr[textField.tag +1];
        }
        
        textField.text = string;
        [textField resignFirstResponder];
        textField.layer.borderColor = LCHexColor(0xE5E5E5).CGColor;
        [nextTextField becomeFirstResponder];
        nextTextField.layer.borderColor = LCHexColor(0xFF7A17).CGColor;
        
         return YES;
       
    }
    else
    {
        UITextField *upTextField = nil;
        if (textField.tag == 0)
        {
            upTextField = self.textFieldArr[textField.tag];
        }
        else
        {
            upTextField = self.textFieldArr[textField.tag -1];
        }
        
        textField.text = @"";
        [textField resignFirstResponder];
        textField.layer.borderColor = LCHexColor(0xE5E5E5).CGColor;
        upTextField.layer.borderColor = LCHexColor(0xFF7A17).CGColor;
        [upTextField becomeFirstResponder];
        
        self.loginButton.enabled = NO;
        [self.loginButton setBackgroundColor:LCHexColor(0xFFBA87)];
        
        return NO;
    }
    
    return YES;
}
@end
